function a(ele){return document.querySelector(ele)}
function c(ele){return document.createElement(ele)}

//ajax_get
function ajax_get(url){
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest()
        xhr.open("get",url,true)
        xhr.send()
        xhr.onreadystatechange=()=>{
            if(xhr.readyState === 4 && xhr.status === 200){
                resolve(xhr.responseText)
            }
        }
    })
}
//ajax_post
function ajax_post(url,str){
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest()
        xhr.open("post",url,true)
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(str)
        xhr.onreadystatechange=()=>{
            if(xhr.readyState === 4 && xhr.status === 200){
                resolve(xhr.responseText)
            }
        }
    })
}

//别的页面能够影响购物车的只有local_collect里的数据！！！



//打开购物车页面就判断是否有shop，shop_total，sum本地仓库，没有就创建
if(!localStorage.getItem("shop")){
    localStorage.setItem("shop","[]")
}
if(!localStorage.getItem("shop_total")){
    localStorage.setItem("shop_total","[]")
}
if(!localStorage.getItem("sum")){
    localStorage.setItem("sum","[]")
}
//打开购物车页面就判断shop_total是否为空,如果是空就将local_collect里的内容拷贝进来
let s2=JSON.parse(localStorage.getItem("shop_total"))
let s3=JSON.parse(localStorage.getItem("local_collect"))
if(s2.length===0){
    for(let i in s3){
        let obj={
            id:s3[i].shop_cart,
            product_num:1
        }
        s2.push(obj)
    }
    localStorage.setItem("shop_total",JSON.stringify(s2))
}
//页面加载时执行的代码
window.onload=()=>{
    ajax_get("./get.php").then(result=>{
        let arr=JSON.parse(result)
        localStorage.setItem("shop",JSON.stringify(arr))
        let shop_arr=JSON.parse(localStorage.getItem("shop"))
        let s2=JSON.parse(localStorage.getItem("shop_total"))
        let s3=JSON.parse(localStorage.getItem("local_collect"))
        //页面加载ajax请求下，并将local_collect和shop_total比较下，将shop_total里的内容完善
            let s1=[]
            for(let j in s3){
                if(s2.includes(s3[j].id)){
                    let obj={
                        id:s2[j].id,
                        product_num:s2[j].product_num
                    }
                    s1.push(obj)
                }else{
                    let obj={
                        id:s3[j].shop_cart,
                        product_num:1
                    }
                    s1.push(obj)
                }
            }
            localStorage.setItem("shop_total",JSON.stringify(s1))
        //将这里的s2作为实参传入create_shop中
        create_shop(shop_arr,s2)
        //判断下地址栏是否有reload(即是否从热点或详细界面跳转过来),如果有浏览器自动刷新一次，以解决一个Bug(该Bug暂时无法解决)
        let url=window.location.href
        let url_str=url.split("?")[1]
        if(url_str == "reload"){
            window.location.reload()
            window.location.href="http://localhost/mogujie/shop-cart.html"
        }
    })
    //如果页面刷新，将sum仓库内的对象product_num全部重置为1
    reset_sum(JSON.parse(localStorage.getItem("sum")))
}
// let total=0
//主页面渲染函数
function create_shop(shop_arr,s2){
    a(".container").innerHTML=""
    let newArr=JSON.parse(localStorage.getItem("local_collect"))
    let dataArr=[]
    let result=[]
    //去重！！
    for(let k in newArr){
        if(!dataArr.includes(newArr[k].shop_cart)){
            dataArr.push(newArr[k].shop_cart)
        }
    }
    //数组间的比较过滤JS取出两个数组相同元素，非常重要！！
    for(let i in shop_arr){
        var obj=shop_arr[i]
        var num1=shop_arr[i].id
        for(let j in dataArr){
            var num2=dataArr[j]
            if(num2 === num1){
                result.push(obj)
            }
        }
    }
    for(let l in result){
        let main=$("<div></div>")
        main.addClass("main").attr("tag",result[l].id)
        let img=$("<img>")
        img.addClass("main-img").attr("src","./img/"+result[l].id+".jpg")
        img.appendTo($(main))
        let name=$("<div></div>")
        name.addClass("name").text(result[l].product_name)
        let size=$("<div></div>")
        size.addClass("size").text(result[l].product_size+"码")
        let box1=$("<div></div>")
        box1.addClass("box1").append($(name).append($(size)))
        let price=$("<div></div>")
        price.addClass("price").text("￥"+result[l].product_price)
        let cut=$("<input>")
        cut.attr("id","cut").attr("type","button").val("-").attr("tag",result[l].id)
        let show_num=$("<input>")
        show_num.attr("id","show_num").val(function(){
            let c=JSON.parse(localStorage.getItem("shop_total"))
            let newArr=c.filter((item3)=>{
                return item3.id === result[l].id
            })
            return newArr[0].product_num
        })
        let add=$("<input>")
        add.attr("id","add").attr("type","button").val("+").attr("tag",result[l].id)
        let num=$("<div></div>")
        num.addClass("num").append($(cut)).append($(show_num)).append($(add))
        let box2=$("<div></div>")
        box2.addClass("box2").append($(price).append($(num)))
        let select=$("<input>")
        select.attr("id","select").attr("type","checkbox").attr("tag",result[l].id)
        //点击checkbox触发计算总和
        select.on("click",function(){
            let total=0
            let data=JSON.parse(localStorage.getItem("sum"))
            //当select被选中时执行
            if($(this).prop("checked")){
                let newArr1=result.filter((item)=>{
                    return item.id == $(this).attr("tag")
                })
                let newArr2=s2.filter((item)=>{
                    return item.id == $(this).attr("tag")
                })
                let obj={
                    id:$(this).attr("tag"),
                    product_price:newArr1[0].product_price,
                    product_num:newArr2[0].product_num
                }
                if(data.length <= 0){
                    data.push(obj)
                }
                if(!data.find((item)=>{return item.id == $(this).attr("tag")})){
                    data.push(obj)
                    localStorage.setItem("sum",JSON.stringify(data))
                }else{
                    let newArr3=data.filter((item)=>{return item.id == $(this).attr("tag")})
                    newArr3[0].product_num=obj.product_num
                    localStorage.setItem("sum",JSON.stringify(data))
                }
                let sum_arr=JSON.parse(localStorage.getItem("sum"))
                total=sum(sum_arr)
                $(".total h4").text(total)
            }else{ //当select取消选中时执行
                let del_arr=JSON.parse(localStorage.getItem("sum"))
                let newArr=del_arr.filter((item)=>{
                    return item.id == $(this).attr("tag")
                })
                let index=del_arr.indexOf(newArr[0])
                del_arr.splice(index,1)
                localStorage.setItem("sum",JSON.stringify(del_arr))
                //重新获取sum仓库数据，重新计算总和
                let sum_arr=JSON.parse(localStorage.getItem("sum"))
                total=sum(sum_arr)
                $(".total h4").text(total)
            }
        })
        let form=$("<form></form>")
        form.attr("id","form").append($(select))
        let right=$("<div></div>")
        right.addClass("right").append($(box1)).append($(box2)).append($(form))
        main.append($(right))
        $(".container").append($(main))
        //为减少按钮添加点击事件
        cut.on("click",function(){
            let data1=s2.filter((item1)=>{
                return item1.id === $(this).attr("tag")
            })
            if(data1[0].product_num<=1){
                alert("商品数量不能少于1")
            }else{
                let data2=s2.filter((item2)=>{
                    if(item2.id === $(this).attr("tag")){
                        item2.product_num--
                    }
                    return this
                })
                localStorage.setItem("shop_total",JSON.stringify(data2))
            }
            ajax_get("./get.php").then(result=>{
                let arr=JSON.parse(result)
                localStorage.setItem("shop",JSON.stringify(arr))
                let shop_arr=JSON.parse(localStorage.getItem("shop"))
                create_shop(shop_arr,s2)
            })
        })
        //为增加按钮添加点击事件
        add.on("click",function(){
            let data1=s2.filter((item1)=>{
                return item1.id === $(this).attr("tag")
            })
            if(data1[0].product_num>=result[l].product_num){
                alert("超出商品最大数量")
            }else{
                let data2=s2.filter((item2)=>{
                    if(item2.id === $(this).attr("tag")){
                        item2.product_num++
                    }
                    return this
                })
                localStorage.setItem("shop_total",JSON.stringify(data2))
            }
            ajax_get("./get.php").then(result=>{
                let arr=JSON.parse(result)
                localStorage.setItem("shop",JSON.stringify(arr))
                let shop_arr=JSON.parse(localStorage.getItem("shop"))
                create_shop(shop_arr,s2)
            })
        })
        // total +=result[l].product_price*show_num.val()
    }
    // $(".total h4").text(total)
}


//计算价格总和函数
function sum(sum_arr){
    let a=0
    for(let i of sum_arr){
        a=a+i.product_num*i.product_price
    }
    return a
}


//结算按钮
$("#btn_account").on("click",function(){
    let arr=JSON.parse(localStorage.getItem("shop_total"))
    let data=JSON.parse(localStorage.getItem("shop"))
    for(let i of arr){
        let a=data.filter((item)=>{
            return item.id === i.id
        })
        let b=a[0].product_num-i.product_num
        let str="id="+i.id+"&product_num="+b
        ajax_post("./account_post.php",str).then(result=>{      
            console.log(result)
        })

    }
    ajax_get("./get.php").then(result=>{
        let arr=JSON.parse(result)
        localStorage.setItem("shop",JSON.stringify(arr))
        let shop_arr=JSON.parse(localStorage.getItem("shop"))
        let s2=JSON.parse(localStorage.getItem("shop_total"))
        let s3=JSON.parse(localStorage.getItem("local_collect"))
        //页面加载ajax请求下，并将local_collect和shop_total比较下，将shop_total里的内容完善
            let s1=[]
            for(let j in s3){
                if(s2.includes(s3[j].id)){
                    let obj={
                        id:s2[j].id,
                        product_num:s2[j].product_num
                    }
                    s1.push(obj)
                }else{
                    let obj={
                        id:s3[j].shop_cart,
                        product_num:1
                    }
                    s1.push(obj)
                }
            }
            localStorage.setItem("shop_total",JSON.stringify(s1))
        //将这里的s2作为实参传入create_shop中
        create_shop(shop_arr,s2)
    })                                                     
})
//删除按钮
$("#btn_del").on("click",function(){
    let data1=JSON.parse(localStorage.getItem("shop_total"))
    let data2=JSON.parse(localStorage.getItem("local_collect"))
    let data3=JSON.parse(localStorage.getItem("sum"))
    let str=""
    $("input:checkbox:checked").each(function(){
        str=str+$(this).attr("tag")
        return str
    })
    let arr=str.split("")
    for(let i of arr){
        let newArr=data1.filter((item)=>{
            return item.id === i
        })
        let index=data1.indexOf(newArr[0])
        data1.splice(index,1)
    }
    localStorage.setItem("shop_total",JSON.stringify(data1))
    for(let j of arr){
        let newArr=data2.filter((item)=>{
            return item.shop_cart === j
        })
        let index=data2.indexOf(newArr[0])
        data2.splice(index,1)
    }
    localStorage.setItem("local_collect",JSON.stringify(data2))
    for(let k of arr){
        let newArr=data3.filter((item)=>{
            return item.id === k
        })
        let index=data3.indexOf(newArr[0])
        data3.splice(index,1)
    }
    localStorage.setItem("sum",JSON.stringify(data3))

    //重新获取sum仓库数据，重新计算总和
    let sum_arr=JSON.parse(localStorage.getItem("sum"))
    total=sum(sum_arr)
    $(".total h4").text(total)

    ajax_get("./get.php").then(result=>{
        let arr=JSON.parse(result)
        localStorage.setItem("shop",JSON.stringify(arr))
        let shop_arr=JSON.parse(localStorage.getItem("shop"))
        let s2=JSON.parse(localStorage.getItem("shop_total"))
        let s3=JSON.parse(localStorage.getItem("local_collect"))
        //页面加载ajax请求下，并将local_collect和shop_total比较下，将shop_total里的内容完善
            let s1=[]
            for(let j in s3){
                if(s2.includes(s3[j].id)){
                    let obj={
                        id:s2[j].id,
                        product_num:s2[j].product_num
                    }
                    s1.push(obj)
                }else{
                    let obj={
                        id:s3[j].shop_cart,
                        product_num:1
                    }
                    s1.push(obj)
                }
            }
            localStorage.setItem("shop_total",JSON.stringify(s1))
        //将这里的s2作为实参传入create_shop中
        create_shop(shop_arr,s2)
    })
})

//reset_sum函数
function reset_sum(arr){
    for(let i of arr){
        i.product_num=1
    }
    localStorage.setItem("sum",JSON.stringify(arr))
    $(".total h4").text(0)
}